package org.jeecg.modules.online.cgreport.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.io.OutputStream;
import java.lang.invoke.SerializedLambda;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.TuringBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.DynamicDataSourceModel;
import org.jeecg.common.util.BrowserUtils;
import org.jeecg.common.util.SqlInjectionUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.security.JdbcSecurityUtil;
import org.jeecg.modules.online.cgform.utils.CgformUtil;
import org.jeecg.modules.online.cgreport.constant.CgReportConstant;
import org.jeecg.modules.online.cgreport.entity.OnlCgreportHead;
import org.jeecg.modules.online.cgreport.entity.OnlCgreportItem;
import org.jeecg.modules.online.cgreport.entity.OnlCgreportParam;
import org.jeecg.modules.online.cgreport.mapper.OnlCgreportHeadMapper;
import org.jeecg.modules.online.cgreport.service.IOnlCgreportItemService;
import org.jeecg.modules.online.cgreport.service.IOnlCgreportParamService;
import org.jeecg.modules.online.cgreport.service.impl.OnlCgreportAPIService;
import org.jeecg.modules.online.cgreport.service.impl.OnlCgreportHeadServiceImpl;
import org.jeecg.modules.online.cgreport.util.CgReportSqlUtil;
import org.jeecg.modules.online.config.p021c.OnlReportQueryBlackListHandler;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping({"/online/cgreport/api"})
@RestController("onlCgreportAPI")
public class OnlCgreportAPI {

    /* renamed from: a */
    private static final Logger f465a = LoggerFactory.getLogger(OnlCgreportAPI.class);
    @Autowired
    private OnlCgreportAPIService cgreportAPIService;
    @Autowired
    private OnlCgreportHeadServiceImpl onlCgreportHeadService;
    @Autowired
    private IOnlCgreportItemService onlCgreportItemService;
    @Autowired
    @Lazy
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IOnlCgreportParamService onlCgreportParamService;
    @Autowired
    private OnlReportQueryBlackListHandler onlReportQueryBlackListHandler;


    @GetMapping({"/getColumnsAndData/{code}"})
    public Result<?> getColumnsAndData(@PathVariable("code") String str, HttpServletRequest httpServletRequest) {
        OnlCgreportHead onlCgreportHead = this.onlCgreportHeadService.getById(str);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        Result<?> m132b = m132b(str, httpServletRequest);
        if (m132b.getCode().equals(200)) {
            List<Map<String, Object>> list = (List) ((Map) m132b.getResult()).get("records");
            Map<String, Object> queryColumnInfo = this.onlCgreportHeadService.queryColumnInfo(str, false);
            JSONArray jSONArray = (JSONArray) queryColumnInfo.get("columns");
            HashMap hashMap = new HashMap(5);
            if (jSONArray != null) {
                for (int i = 0; i < jSONArray.size(); i++) {
                    JSONObject jSONObject = jSONArray.getJSONObject(i);
                    Object obj = jSONObject.get("dictCode");
                    if (obj != null) {
                        String obj2 = obj.toString();
                        String string = jSONArray.getJSONObject(i).getString("dataIndex");
                        List<DictModel> queryColumnDictList = this.onlCgreportHeadService.queryColumnDictList(obj2, list, string);
                        if (queryColumnDictList != null) {
                            hashMap.put(string, queryColumnDictList);
                            jSONObject.put("customRender", string);
                        }
                    }
                }
            }
            queryColumnInfo.put("cgreportHeadName", onlCgreportHead.getName());
            queryColumnInfo.put("data", m132b.getResult());
            queryColumnInfo.put("dictOptions", hashMap);
            return Result.ok(queryColumnInfo);
        }
        return m132b;
    }

    @GetMapping({"/getColumns/{code}"})
    @Deprecated
    /* renamed from: a */
    public Result<?> getColumns(@PathVariable("code") String str) {
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getById(str);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cgrhead_id", str);
        queryWrapper.eq("is_show", 1);
        queryWrapper.orderByAsc("order_num");
        List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);
        ArrayList arrayList = new ArrayList();
        HashMap hashMap = new HashMap(5);
        for (OnlCgreportItem onlCgreportItem : list) {
            HashMap hashMap2 = new HashMap(5);
            hashMap2.put(CgformUtil.f298aR, onlCgreportItem.getFieldTxt());
            hashMap2.put("dataIndex", onlCgreportItem.getFieldName());
            hashMap2.put("align", CgformUtil.f291aK);
            hashMap2.put("sorter", "true");
            arrayList.add(hashMap2);
            String dictCode = onlCgreportItem.getDictCode();
            if (oConvertUtils.isNotEmpty(dictCode)) {
                List list2 = null;
                if (dictCode.toLowerCase().indexOf("select ") == 0) {
                    this.sysBaseAPI.dictTableWhiteListCheckByDict(dictCode, new String[0]);
                    SqlInjectionUtil.specialFilterContentForOnlineReport(dictCode);
                    List<Map<String, Object>> executeSqlDict = ((OnlCgreportHeadMapper) this.onlCgreportHeadService.getBaseMapper()).executeSqlDict(dictCode);
                    if (executeSqlDict != null && executeSqlDict.size() != 0) {
                        list2 = JSON.parseArray(JSON.toJSONString(executeSqlDict), DictModel.class);
                    }
                } else {
                    list2 = this.sysBaseAPI.queryDictItemsByCode(dictCode);
                }
                if (list2 != null) {
                    hashMap.put(onlCgreportItem.getFieldName(), list2);
                    hashMap2.put("customRender", onlCgreportItem.getFieldName());
                }
            }
        }
        HashMap hashMap3 = new HashMap(1);
        hashMap3.put("columns", arrayList);
        hashMap3.put("dictOptions", hashMap);
        hashMap3.put("cgreportHeadName", onlCgreportHead.getName());
        return Result.ok(hashMap3);
    }

    @GetMapping({"/getData/{code}"})
    public Result<?> m132b(@PathVariable("code") String str, HttpServletRequest httpServletRequest) {
        Map<String, Object> m97a = CgReportSqlUtil.m97a(httpServletRequest);
        m97a.put("getAll", httpServletRequest.getAttribute("getAll"));
        try {
            return Result.OK(this.cgreportAPIService.getDataById(str, m97a));
        } catch (TuringBootException e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping({"/getDataOrderByValue/{code}"})
    public Result<?> getDataOrderByValue(@PathVariable("code") String str, HttpServletRequest httpServletRequest) {
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getById(str);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        String trim = onlCgreportHead.getCgrSql().trim();
        String dbSource = onlCgreportHead.getDbSource();
        try {
            Map<String, Object> m97a = CgReportSqlUtil.m97a(httpServletRequest);
            Object obj = m97a.get(CgReportConstant.f500F);
            Object obj2 = m97a.get(CgReportConstant.f501G);
            if (oConvertUtils.isEmpty(obj) || oConvertUtils.isEmpty(obj2)) {
                return Result.error("order_field 和 order_value 参数不能为空！");
            }
            String str2 = CgReportConstant.f499E + obj;
            m97a.put(str2, obj2);
            m97a.put("getAll", true);
            JSONArray parseArray = JSON.parseArray(JSON.toJSONString(this.cgreportAPIService.executeSelectSqlRoute(dbSource, trim, m97a, onlCgreportHead.getId()).get("records")));
            m97a.remove(obj.toString());
            m97a.remove(str2);
            m97a.remove(CgReportConstant.f500F);
            m97a.remove(CgReportConstant.f501G);
            m97a.put("getAll", httpServletRequest.getAttribute("getAll"));
            Map<String, Object> executeSelectSqlRoute = this.cgreportAPIService.executeSelectSqlRoute(dbSource, trim, m97a, onlCgreportHead.getId());
            JSONArray parseArray2 = JSON.parseArray(JSON.toJSONString(executeSelectSqlRoute.get("records")));
            m141a(parseArray, parseArray2, obj.toString());
            executeSelectSqlRoute.put("records", parseArray2);
            return Result.ok(executeSelectSqlRoute);
        } catch (Exception e) {
            f465a.error(e.getMessage(), e);
            return Result.error("SQL执行失败：" + e.getMessage());
        }
    }

    /* renamed from: a */
    private void m141a(JSONArray jSONArray, JSONArray jSONArray2, String str) {
        for (int i = 0; i < jSONArray.size(); i++) {
            JSONObject jSONObject = jSONArray.getJSONObject(i);
            String string = jSONObject.getString(str);
            if (string != null && ((int) jSONArray2.stream().filter(obj -> {
                return string.equals(((JSONObject) obj).getString(str));
            }).count()) == 0) {
                jSONArray2.add(0, jSONObject);
            }
        }
    }

    @GetMapping({"/getQueryInfo/{code}"})
    /* renamed from: b */
    public Result<?> getQueryInfo(@PathVariable("code") String str) {
        try {
            return Result.ok(this.onlCgreportItemService.getAutoListQueryInfo(str));
        } catch (Exception e) {
            return Result.error("查询失败");
        }
    }

    @GetMapping({"/getParamsInfo/{code}"})
    /* renamed from: c */
    public Result<?> getParamsInfo(@PathVariable("code") String str) {
        try {
        	LambdaQueryWrapper<OnlCgreportParam> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(OnlCgreportParam::getCgrheadId, str);
            lambdaQueryWrapper.orderByAsc(OnlCgreportParam::getOrderNum);
            return Result.ok(this.onlCgreportParamService.list(lambdaQueryWrapper));
        } catch (Exception e) {
            return Result.error("查询失败");
        }
    }

    @RequestMapping({"/exportManySheetXls/{reportId}"})
    public void exportManySheetXls(@PathVariable("reportId") String str, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        if (oConvertUtils.isEmpty(str)) {
            throw new TuringBootException("参数错误");
        }
        Workbook reportWorkbook = this.cgreportAPIService.getReportWorkbook(str, CgReportSqlUtil.m97a(httpServletRequest));
        httpServletResponse.setContentType("application/vnd.ms-excel");
        OutputStream outputStream = null;
        try {
            try {
                if ("MSIE".equalsIgnoreCase(BrowserUtils.checkBrowse(httpServletRequest).substring(0, 4))) {
                    httpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("报表", "UTF-8") + ".xls");
                } else {
                    httpServletResponse.setHeader("content-disposition", "attachment;filename=" + new String("报表".getBytes("UTF-8"), "ISO8859-1") + ".xls");
                }
                outputStream = httpServletResponse.getOutputStream();
                reportWorkbook.write(outputStream);
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                }
            } catch (Exception e2) {
                f465a.warn("导出失败", e2.getMessage());
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e3) {
                }
            }
        } catch (Throwable th) {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (Exception e4) {
            }
            throw th;
        }
    }

    @GetMapping({"/getRpColumns/{code}"})
    /* renamed from: d */
    public Result<?> getRpColumns(@PathVariable("code") String str) {
    	LambdaQueryWrapper<OnlCgreportHead> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(OnlCgreportHead::getCode, str);
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getOne(lambdaQueryWrapper);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        Map<String, Object> queryColumnInfo = this.onlCgreportHeadService.queryColumnInfo(onlCgreportHead.getId(), true);
        queryColumnInfo.put("cgRpConfigId", onlCgreportHead.getId());
        queryColumnInfo.put("cgRpConfigName", onlCgreportHead.getName());
        return Result.ok(queryColumnInfo);
    }

    @PostMapping({"/testConnection"})
    @RequiresPermissions({"online:report:testConnection"})
    /* renamed from: a */
    public Result testConnection(@RequestBody DynamicDataSourceModel dynamicDataSourceModel) {
        Connection connection = null;
        try {
            JdbcSecurityUtil.validate(dynamicDataSourceModel.getDbUrl());
            Class.forName(dynamicDataSourceModel.getDbDriver());
            Connection connection2 = DriverManager.getConnection(dynamicDataSourceModel.getDbUrl(), dynamicDataSourceModel.getDbUsername(), dynamicDataSourceModel.getDbPassword());
            if (connection2 != null) {
                Result ok = Result.ok("数据库连接成功");
                if (connection2 != null) {
                    try {
                        if (!connection2.isClosed()) {
                            connection2.close();
                        }
                    } catch (SQLException e) {
                        f465a.error(e.toString());
                    }
                }
                return ok;
            }
            Result ok2 = Result.ok("数据库连接失败：错误未知");
            return ok2;
        } catch (ClassNotFoundException e3) {
            f465a.error(e3.toString());
            Result error = Result.error("数据库连接失败：驱动类不存在");
            return error;
        } catch (Exception e1) {
			// TODO Auto-generated catch block
        	Result ok2 = Result.ok("数据库连接失败：错误未知");
            return ok2;
		} 
    }

    @RequiresPermissions({"online:report:getDictList"})
    @GetMapping({"/getReportDictList"})
    /* renamed from: a */
    public Result<?> getReportDictList(@RequestParam("fieldId") String str, @RequestParam(name = "keyword", required = false) String str2, @RequestParam(name = "pageNo", defaultValue = "1") Integer num, @RequestParam(name = "pageSize", defaultValue = "10") Integer num2) {
        OnlCgreportItem onlCgreportItem = (OnlCgreportItem) this.onlCgreportItemService.getById(str);
        if (onlCgreportItem == null) {
            throw new TuringBootException("指定字段不存在");
        }
        return Result.ok(this.onlCgreportHeadService.queryDictSelectData(onlCgreportItem.getDictCode(), str2, num.intValue(), num2.intValue()));
    }
}
